import hashlib
import smtplib
import random
from django.core.cache import cache
from email.mime.text import MIMEText
from django.shortcuts import render
from models.models.RequestResult import RequestResult as Res
from django.http import HttpResponseRedirect as Response
from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse
from models.models.StoreUser import StoreUser


# 登录
@csrf_exempt
def login(request):
    user_email = request.POST.get("user_email")
    user_pass = request.POST.get("user_pass")
    user = StoreUser.objects.filter(user_email=user_email).first()
    if user is not None:
        if user.user_pass == hashlib.md5(user_pass.encode()).hexdigest():
            # 登录成功，添加session
            request.session["user"] = user.to_dict()
            return JsonResponse(Res.success(None))
    return JsonResponse(Res.error(500, "用户名或密码错误"))


# 注册
@csrf_exempt
def reg(request):
    user_email = request.POST.get("user_email")
    user_pass = request.POST.get("user_pass")
    nick_name = request.POST.get("nick_name")
    auth_code = request.POST.get("auth_code")
    redis_code = cache.get(user_email+"_auth_code")
    if auth_code != redis_code:
        return JsonResponse(Res.error(500, "验证码错误"))
    cache.delete(user_email+"_auth_code")
    user = StoreUser.objects.filter(user_email=user_email).first()
    if not user:
        user = StoreUser()
        user.user_email = user_email
        user.user_pass = hashlib.md5(user_pass.encode()).hexdigest()
        user.nick_name = nick_name
        user.save()
        return JsonResponse(Res.success(None))
    else:
        return JsonResponse(Res.error(500, "该邮箱号已注册"))


# 获取验证码
@csrf_exempt
def get_auth_code(request):
    code_type = request.POST.get("code_type")
    user_email = request.POST.get("user_email")
    # 设置服务器所需信息
    # 163邮箱服务器地址
    mail_host = 'smtp.163.com'
    # 163用户名
    mail_user = 'apeblog@163.com'
    # 密码(部分邮箱为授权码)
    mail_pass = 'IKKIWJGBSLRSEBYB'
    # 邮件发送方邮箱地址
    sender = mail_user
    # 邮件接受方邮箱地址，注意需要[]包裹，这意味着你可以写多个邮件地址群发
    receivers = [user_email]

    # 设置email信息
    # 邮件内容设置
    # 生成随机验证码
    code = ""
    for i in range(6):
        code += str(random.randint(0, 9))
    message = MIMEText("【爱优惠商城】您的验证码为："+code+"，30分钟内有效，请勿告知他人。", "plain", 'utf-8')
    # 邮件主题
    if code_type == "reg":
        message['Subject'] = "【爱优惠商城】注册验证码"
    elif code_type == "reset":
        message['Subject'] = "【爱优惠商城】重置密码验证码"
    # 发送方信息
    message['From'] = sender
    # 接受方信息
    message['To'] = receivers[0]
    # 登录并发送邮件
    try:
        smtp_obj = smtplib.SMTP()
        # 连接到服务器
        smtp_obj.connect(mail_host, 25)
        # 登录到服务器
        smtp_obj.login(mail_user, mail_pass)
        # 发送
        smtp_obj.sendmail(sender, receivers, message.as_string())
        # 退出
        smtp_obj.quit()
        # 将验证码存放到redis中，设置30分钟有效期
        cache.set(user_email+"_auth_code", code, 30*60)
        return JsonResponse(Res.success(None))
    except smtplib.SMTPException as e:
        return JsonResponse(Res.error(500, e))


# 退出登录
def logout(request):
    del request.session["user"]
    return Response('/')


# 重置密码
@csrf_exempt
def reset_password(request):
    user_email = request.POST.get("user_email")
    user_pass = request.POST.get("user_pass")
    auth_code = request.POST.get("auth_code")
    redis_code = cache.get(user_email+"_auth_code")
    if auth_code != redis_code:
        return JsonResponse(Res.error(500, "验证码错误"))
    cache.delete(user_email+"_auth_code")
    user = StoreUser.objects.filter(user_email=user_email).first()
    if not user:
        return JsonResponse(Res.error(500, "该邮箱号还未注册"))
    else:
        user.user_pass = hashlib.md5(user_pass.encode()).hexdigest()
        user.save()
        if request.session.get("user"):
            del request.session["user"]
        return JsonResponse(Res.success(None))


# 更换头像
@csrf_exempt
def edit_icon(request):
    user_icon = request.POST.get("userIcon")
    user_id = request.session['user'].get("id")
    user = StoreUser.objects.filter(id=user_id).first()
    user.user_icon = user_icon
    user.save()
    request.session["user"] = user.to_dict()
    return JsonResponse(Res.success(None))
